package com.yjkf.zh.admin.controller;

import com.yjkf.zh.admin.aspect.LogAnnotation;
import com.yjkf.zh.admin.dao.SysDeviceMapper;
import com.yjkf.zh.admin.dao.SysUserDeviceMapper;
import com.yjkf.zh.admin.dao.SysUserMapper;
import com.yjkf.zh.admin.model.SysDevice;
import com.yjkf.zh.admin.model.SysDevicePointUnit;
import com.yjkf.zh.admin.model.SysUser;
import com.yjkf.zh.admin.model.SysUserDevice;
import com.yjkf.zh.admin.service.SysPointUnitService;
import com.yjkf.zh.admin.service.SysUserDeviceService;
import com.yjkf.zh.core.http.HttpResult;
import com.yjkf.zh.core.page.PageRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userDevice")
public class SysUserDeviceController {

    @Autowired
    private SysUserDeviceService sysUserDeviceService;

    @Autowired
    private SysDeviceMapper sysDeviceMapper;

    @Autowired
    private SysUserDeviceMapper sysUserDeviceMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPointUnitService sysPointUnitService;

    @PreAuthorize("hasAuthority('sys:device:view')")
    @PostMapping(value = "/findPage")
  //  @LogAnnotation(content = "查看设备授权列表")
    public HttpResult findPage(@RequestBody PageRequest pageRequest, HttpServletRequest request) {
        Long userId = (Long)request.getSession().getAttribute("userId");

        return HttpResult.ok(sysUserDeviceService.findPage2(pageRequest,userId));
    }

    @PreAuthorize("hasAuthority('sys:device:add') AND hasAuthority('sys:device:edit')")
    @PostMapping(value = "/save")
    @LogAnnotation(content = "授权/编辑设备操作")
    public HttpResult save(@RequestBody SysUserDevice sysUserDevice, HttpServletRequest request){
        Long id = (Long) request.getSession().getAttribute("userId");
        if(sysUserDevice.getId()==0) {
            //根据用户Id与用户名称，判断是否为空
            SysUserDevice sysUserDevice1 = sysUserDeviceMapper.findByIdAndName(id,sysUserDevice.getNickDeviceName());
            if(sysUserDevice1!=null){
                return HttpResult.error("对不起，名称重复，请从新输入");
            }
        }

            List<SysUserDevice> ud = sysUserDeviceMapper.findfind(id);
            if(sysUserDevice.getType()==0){
                sysUserDevice.setParentDeviceId(0L);
            }
            String ident = sysUserDevice.getDeviceIdent();
            if(sysUserDevice.getId()==0||sysUserDevice.getId()==null){
                sysUserDevice.setCreateId(id);
            }
            if(sysUserDevice.getType()==0) {
                if(sysUserDevice.getPointNums()>48){
                    return HttpResult.error("通道数量不能超过48！");
                }
                if (sysDeviceMapper.findDeviceForIdent(ident).isEmpty()) {
                    return HttpResult.error("该设备标识不存在！");
                }
                if (sysUserDevice.getDeviceIdent().isEmpty()) {
                    return HttpResult.error("设备标识不能为空");
                }
                if(sysUserDevice.getId()==0) {
                    for (SysUserDevice sud : ud) {
                        if (sysUserDevice.getDeviceIdent().equals(sud.getDeviceIdent())) {
                            return HttpResult.error("该设备标识已被您注册！");
                        }
                    }
                }
                SysDevice sysDevice = sysDeviceMapper.findDeviceNameForIdent(ident);
                sysUserDevice.setDeviceId(sysDevice.getId());
            }

            if(sysUserDevice.getType()==1){
                //获取父设备
               Long parentDeviceId=sysUserDevice.getParentDeviceId();
               //获取父设备及其子设备的通道数量
                SysUserDevice sysUserDevice1 = sysUserDeviceService.findForParentDeviceId(parentDeviceId);
                Long parentPointNums = sysUserDevice1.getPointNums();
         /*       if(sysUserDevice.getPointNums()>parentPointNums){
                    return HttpResult.error("通道数量不能大于设备组");
                }*/
                List<SysUserDevice> sysUserDevices = sysUserDeviceService.findListForParentDeviceId(parentDeviceId);
                Long dss=(long)sysUserDevices.size();
                sysUserDevice.setDeviceIdent(sysUserDevice1.getDeviceIdent()+"_"+dss);
                Long pointNums = sysUserDevice.getPointNums();
                Long sum= sysUserDevices .stream().collect(Collectors.summingLong(SysUserDevice::getPointNums));
                //获取要增加的设备通道数量
                Long muns=parentPointNums-sum;
                if(pointNums>muns&&sysUserDevice.getId()==0){
                    return HttpResult.error("通道数量超量了");
                }

                /*if(sysUserDevice.getId()!=0){
                    SysUserDevice sysUserDevice2 = sysUserDeviceMapper.findPointNum(sysUserDevice.getId());
                    Long mum=sum-sysUserDevice2.getPointNums()+sysUserDevice.getPointNums();
                    if(parentPointNums<mum){
                        return HttpResult.error("通道数量超量了");
                    }
                }*/

            }
            //    if(sysDevice!=null){
                 sysUserDevice.setUserId(id);

            //  }

        return HttpResult.ok(sysUserDeviceService.save(sysUserDevice));
    }

    @GetMapping("/findDeviceCount")
    public HttpResult findUserDeviceCount(HttpServletRequest request){
        Long id = (Long)request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserDeviceMapper.findUserDeviceCount(id));
    }

    @PreAuthorize("hasAuthority('sys:device:delete')")
    @PostMapping(value = "/delete")
    @LogAnnotation(content = "删除用户绑定的设备")
    public HttpResult delete(@RequestBody List<SysUserDevice> sysUserDevices, HttpServletRequest request){
        Long userId = (Long)request.getSession().getAttribute("userId");
       // System.out.println("当前用户ID:"+userId);
       /* List<SysUser> user=sysUserMapper.findCreateId(userId);      //获取自己创建的用户信息集合
        for(SysUserDevice sysUserDevice : sysUserDevices){          //遍历要删除的授权设备集合
            SysUserDevice sysUserDevicee = sysUserDeviceMapper.findById(sysUserDevice.getId());
            if(!sysUserDeviceService.findListForParentDeviceId(sysUserDevice.getId()).isEmpty()){
                return HttpResult.error("存在子设备，无法删除");
            }
            for(SysUser sysUser :user){                 //遍历自己创建的用户
                    List<SysUserDevice> sysUserDevices1 = sysUserDeviceMapper.findByUserId(sysUser.getId());        //获取创建的用户的设备集合
                    for(SysUserDevice sud: sysUserDevices1){                        //遍历创建的用户的设备
                        if(sud.getDeviceId().equals(sysUserDevicee.getDeviceId())){      //如果遍历出的设备Id等于要删除的授权设备集合
                            return HttpResult.error("该设备存在绑定用户，请解绑后在删除!");
                        }
                    }
            }
        }*/
        return HttpResult.ok(sysUserDeviceService.deleteUserDevices(sysUserDevices,userId));
    }

    //获取指定用户的绑定设备信息
    @GetMapping("/devices")
    public HttpResult findDevice(@RequestParam Long userId){
        return HttpResult.ok(sysUserDeviceMapper.findfind(userId));
    }

    //获取当前用户绑定的设备信息
    @GetMapping("/deviceForUser")
    public HttpResult findDeviceForUser(@RequestParam Long id,HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserDeviceService.findByIdForUser(id,userId));
    }

    @GetMapping("/findUserDeviceById")
    public HttpResult findDeviceById(@RequestParam Long id){
        return HttpResult.ok(sysUserDeviceMapper.findById(id));
    }

    @GetMapping("/findDeviceName")
    public HttpResult findDeviceName(@RequestParam Long id){
        return HttpResult.ok(sysUserDeviceMapper.findPointNum(id));
    }

    @GetMapping("/getDeviceName")
    public HttpResult getDeviceName(@RequestParam String deviceName, HttpServletRequest request){
        SysDevice sysDevice = sysDeviceMapper.getDeviceForDeviceName(deviceName);
        Long userId = (Long) request.getSession().getAttribute("userId");
        Long deviceId = sysDevice.getId();

        return HttpResult.ok(sysUserDeviceMapper.getUserDeviceName(deviceId,userId));

    }

    @GetMapping("/getDeviceId")
    public HttpResult getDeviceId(@RequestParam Long userDeviceId){
        return HttpResult.ok(sysUserDeviceMapper.getDeviceId(userDeviceId));
    }

    //获取用户设备组列表
    @GetMapping("/queryDevices")
    public HttpResult queryDevices(HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserDeviceService.queryDevices(userId));
    }

    @GetMapping("/findDeviceTree")
    public HttpResult findDeviceTree(@RequestParam String deviceName,HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserDeviceService.findDeviceTree(deviceName,userId));
    }

    //获取设备组中全部设备的数据
    @GetMapping("/getDevicesPoints")
    public HttpResult getDevicesPoints(@RequestParam Long userDeviceId,HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("userId");
        List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findByIdForUserId(userDeviceId,userId);
        System.out.println(sysUserDevices.isEmpty());
        List<SysDevicePointUnit> sysUserDeviceList  = new ArrayList<>();
        if(sysUserDevices.isEmpty()){
            sysUserDeviceList.addAll(sysPointUnitService.findAllById(userDeviceId,request));
        }
      else {
            for (SysUserDevice sysUserDevice : sysUserDevices) {
                sysUserDeviceList.addAll(sysPointUnitService.findAllById(sysUserDevice.getId(), request));
            }
        }
        return HttpResult.ok(sysUserDeviceList);
    }

    //根据设备标识符获取用户列表
    @GetMapping("/getUsersForIdent")
    public HttpResult getUsersForIdent(@RequestParam String deviceIdent,HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserDeviceService.getUserForIdent(deviceIdent,userId));
    }

    @PostMapping("/subUserDevice")
    public HttpResult subUserDevice(@RequestBody List<SysUser> sysUsers,HttpServletRequest request){
        Long selfId = (Long) request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserDeviceService.upUserForDevice(sysUsers,selfId));
    }

}
